package com.dc.aimc.auth.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dc.aimc.common.service.util.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AimcAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${jwt.expires}")
    private Long expires;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 响应格式 响应状态码
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setStatus(200);

        // 生成token
        Map<String, Object> info = new HashMap<>();
        info.put("jti", UUID.randomUUID().toString());
        info.put("username", authentication.getName());
        List<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        info.put("authorities", authorities);
        Date expireDate = new Date(System.currentTimeMillis() + expires);
        info.put("exp", expireDate.getTime() / 1000);
        String token = JwtUtil.signToken(info, expireDate);

        // 封装token信息
        Map<String, Object> data = new HashMap<>();
        data.put("access_token", token);
        data.put("token_type", "bearer");
        data.put("expires_in", (expireDate.getTime() - System.currentTimeMillis()) / 1000);

        // 响应
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(data, SerializerFeature.WriteMapNullValue));
        writer.flush();
        writer.close();
    }

}
